package com.demo.exception;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.ClassPathResource;


/**
 * 获取自定义异常日志信息yml
 */
@Configuration
public class ExceptionMsgConfig {

    private PropertySource propertySource;

    @Autowired
    private PropertySourcesPlaceholderConfigurer properties;

    private static PropertySourcesPlaceholderConfigurer propertySources_placeholderConfigurer;

    private final static Logger logger = LoggerFactory.getLogger(ExceptionMsgConfig.class);


    @Bean
    private static PropertySourcesPlaceholderConfigurer properties() {
        logger.info("--------------  load custom exception yml ----------------------");
        PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer = new PropertySourcesPlaceholderConfigurer();
        YamlPropertiesFactoryBean yml = new YamlPropertiesFactoryBean();
        yml.setResources(new ClassPathResource("custom/exception_msg.yml"));
        propertySourcesPlaceholderConfigurer.setProperties(yml.getObject());
        propertySources_placeholderConfigurer = propertySourcesPlaceholderConfigurer;
        return propertySourcesPlaceholderConfigurer;
    }

    private PropertySource getPropertySource (){
        if (propertySource==null) {
            if(properties==null) {
                properties = propertySources_placeholderConfigurer;
            }
            propertySource = properties.getAppliedPropertySources().get(PropertySourcesPlaceholderConfigurer.LOCAL_PROPERTIES_PROPERTY_SOURCE_NAME);
        }
        return propertySource;
    }

    /**
     *  获取属性值
     * @param errorCode 异常代码
     * @return 异常信息
     */
    public String get (Integer errorCode, String...replaceStr) {
        String key = "ex_"+errorCode;
        Object obj = getPropertySource().getProperty(key);
        if(obj==null) {
            logger.error("exception `" + key + "` not exist!");
            return null;
        }
        if (replaceStr!=null)
            return String.format(obj.toString(),replaceStr);
        return obj.toString();
    }

}
